import { Injectable } from '@nestjs/common'
import { CreateBetDto } from './dto/create-bet.dto'
import { UpdateBetDto } from './dto/update-bet.dto'
import { PrismaService } from 'src/prisma/prisma.service'
import { TowerService } from 'src/tower/tower.service'

@Injectable()
export class BetService {
  constructor(
    private prisma: PrismaService,
    private tower: TowerService,
  ) {}

  /**
   * 创建一行数据
   * @param createBetDto 传入的数据
   * @returns 传入的数据
   */
  async create(createBetDto: CreateBetDto) {
    const { btName, sectionId } = createBetDto

    // 获取铁塔集合
    const towers = await this.prisma.tower.findMany({ where: { sectionId } })

    // 获取t1,t2两个实体
    const [tName1, tName2] = btName.split('--')
    const t1 = towers.find((t) => t.tName === tName1)
    const t2 = towers.find((t) => t.tName === tName2)

    return await this.prisma.bet.create({
      data: {
        ...createBetDto,
        towers: {
          create: [{ towerId: t1.id }, { towerId: t2.id }],
        },
      },
    })
  }

  /**
   * 获取所有包含sectionId的bets集合
   * @param args 包含sectionId的参数
   * @returns 所有的bet的集合
   */
  async findAll(args: Record<string, any>) {
    const { sectionId, search, page } = args

    return await this.prisma.bet.findMany({
      where: {
        sectionId: +sectionId,
        btName: { contains: search },
      },
      include: { towers: true, across: true },
    })
  }

  findOne(id: number) {
    return `This action returns a #${id} bet`
  }

  /**
   * 更新数据
   * @param id 更新的ID
   * @param updateBetDto 更新的数据
   * @returns 更新的结果
   */
  async update(id: number, updateBetDto: UpdateBetDto) {
    return await this.prisma.bet.update({ where: { id }, data: updateBetDto })
  }

  remove(id: number) {
    return `This action removes a #${id} bet`
  }

  /**
   * 删除sectionId的所有数据
   * @param id sectionId区段编号
   * @returns 删除数据的count
   */
  async removeAll(id: number) {
    return this.prisma.bet.deleteMany({ where: { sectionId: id } })
  }
}
